import dayjs from 'dayjs';

// 日期
export function formatDate(
  date?: string | number | Date | dayjs.Dayjs | null | undefined,
  format = 'YYYY-MM-DD HH:mm:ss',
) {
  return dayjs(date).format(format);
}
// 千 xxk
export const formatTick = (tickItem: string | number) => {
  // 如果 tickItem 是数字，就将其除以 1000 并添加 'k' 后缀
  if (typeof tickItem === 'number') {
    return `${(tickItem / 1000).toFixed(1)}k`;
  }
  // 如果 tickItem 不是数字（例如，自定义刻度），则直接返回
  return tickItem;
};

// 上传文件名
export function formateType(name: string | undefined) {
  const nameList = name?.split('.');
  if (nameList?.length && nameList.length === 2) {
    return nameList[1];
  } else {
    return 'file';
  }
}

// 千分位加 ,
export function formatNumberWithCommas(
  value: string | number,
  separator = ',',
) {
  if (value === null || value === undefined || isNaN(Number(value))) {
    return '0';
  }
  return `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, separator);
}

//  人民币 分转元
export function formatPrice(price?: number) {
  return price ? '¥' + (price / 100).toFixed(2) : '¥0.00';
}

//  人民币 元
export function formatOriginalPrice(price?: number, fixedNumber?: number) {
  return price ? '¥' + price.toFixed(fixedNumber || 2) : '¥0.00';
}

// 过滤对象中值为 null / undefined / '' 的字段
export function formatRequestParams(params: any) {
  return Object.fromEntries(
    Object.entries(params).filter(
      ([_, v]) => v != null && v !== '' && v !== undefined,
    ),
  );
}

export function formatSize(size: number) {
  const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  let i = 0;
  while (size >= 1024) {
    size /= 1024;
    i++;
  }
  return size.toFixed(2) + ' ' + units[i];
}

/**
 *
 * @param {*} dateStr 支持new Date() 的日期字符串
 * @param {*} type max: 23：59：59的时间戳  min: 当日00：00：00的时间戳
 */
export const getDayTimestamp = (dateStr:any, type = 'min') => {
  const _date = dateStr ? new Date(dateStr) : new Date();
  const timestamp = new Date(_date.toLocaleDateString()).getTime();
  return type === 'max' ? timestamp + 86400000 - 1 : timestamp;
};

/**
 *
 * @param data source tree data.
 * @param config field names in each layer of the tree.
 * @returns tree structured data of standard field names. eg: [{label: '', value: '', children: []}]
 */
export const formatTreeData = (data:any, config:any) => {
  const defaultConfig = {
    labelKey: 'label',
    valueKey: 'value',
    childrenKey: 'children',
    disableKey: 'disabled',
  };

  function transformNode(node:any, level = 0) {
    // config of target layer
    const { labelKey, valueKey, childrenKey, disableKey } =
      config[level] || defaultConfig;

    // standard node create
    const result = {
      label: node[labelKey],
      value: node[valueKey],
      children: [],
      disabled: node[disableKey],
    };

    // recursive processing of child nodes
    if (node[childrenKey] && Array.isArray(node[childrenKey])) {
      result.children = node[childrenKey].map((child) =>
        transformNode(child, level + 1),
      ) as any;
    }

    return result;
  }

  // recursive processing of root nodes
  return data.map((node:any) => transformNode(node));
};
